import { asset_types, isPlainObject, mergeOptions } from "../utils";

export function initGlobalAPI(Vue) {
  Vue.options = {};
  // 无论后续创建多个子类 都可以通过_base找到Vue大Vue
  Vue.options._base = Vue;
  asset_types.forEach((type) => {
    Vue.options[type + "s"] = {};
  });
  Vue.mixin = function (mixin) {
    this.options = mergeOptions(this.options, mixin);
    return this;
  };

  // 产生一个继承与Vue的类
  Vue.extend = function (extendOptions) {
    extendOptions = extendOptions || {};
    const Super = this;
    const name = extendOptions.name || Super.options.name;

    const Sub = function VueComponent(options) {
      this._init(options);
    };
    Sub.prototype = Object.create(Super.prototype);
    Sub.prototype.constructor = Sub;
    Sub.options = mergeOptions(Super.options, extendOptions);
    Sub["super"] = Super;
    return Sub;
  };

  Vue.options.components = {};
  Vue.component = function (id, definition) {
    // 保证组件的隔离，每个组件都会产生一个新的类， 去继承父类
    definition = this.options._base.extend(definition);
    this.options.components[id] = definition;
  };

  asset_types.forEach((type) => {
    Vue[type] = function (id, definition) {
      if (!definition) {
        return this.options[type + "s"][id];
      } else {
        if (type === "component" && isPlainObject(definition)) {
          definition.name = definition.name || id;
          definition = this.options._base.extend(definition);
        }
        if (type === "directive" && typeof definition === "function") {
          definition = {
            bind: definition,
            upate: definition,
          };
        }
        this.options[type + "s"][id] = definition;
        return definition;
      }
    };
  });
}
